第一題 [分類器、特徵建構、與Stacking]

(50%) 建構分類器時常會透過特徵選擇與Ensemble增強預測能力。本題的目的是讓大家練習這些技巧。本題使用一個中文姓名分類的資料集。這個資料集收集了10730個中文名(不含姓),以及這些名子對應到的性別。本資料集的資料檔是namesex_data_v2.csv,共有三個欄位,gname, sex, fold:

我們先將這個資料集讀入Numpy Array,並列印前十筆資料

接下來看一些統計數字:

這個資料集的男女比率還算是平均,男性佔了47.94%。

我們用了比較迂迴的方式讀檔案,Pandas其實可以直接讀csv檔。接下來做一些基本的資料分析。我們關心幾件事:

要回答這些問題,首先對名子加總,計算數量與男性比率,排序之後列出前20個名子:

由上面的列表看來,最常見的男性名子是承恩與冠廷,最常見的女性名子是宜蓁與佳穎。而這些常見的名子男性比率都非常接近0或1,表示這些名子沒有性別混淆的問題。

另外一個問題是有多少名子只出現一次:

由結果看來,名子在資料集中只出現一次的比率很高,有65%。也就是說,如果單純的使用訓練資料中出現的名子做為特徵,模型應該會有很差的預測能力。

為了處理這個問題,我們在接下來的任務中,會使用"Unigram + Full Name"的特徵表示,比如說,"芳瑜"的特徵表示為"芳"、"瑜",以及原始的名子"芳瑜"。

最後我們來看看性別混淆的名子:

難以區分性別的名子總數並不高,所占總體資料的比率也很低,只有1.26%,因此不用擔心這個因素會影響預測準確率。

下面來看看幾個容易混淆性別的名子:

實做限制

為了確保可以確實練習到重要技巧,禁用Pycaret (https://pycaret.org/) 這類可以自動化調教參數與Ensemble模型的工具。另外也禁止使用sklearn.ensemble.Stacking.*。你可以使用sklearn中Pre-processing工具函數與現成的分類器,但參數調教請自行處理。

回答下面問題

Q1.1 (10%):

使用One-hot Encoding建構資料變數。所有資料變數都要是Numpy Array。依照每筆資料其fold值切割為Training (fold <=6)、Validation (fold == 7)、Stacking (fold == 8)、Test (fold == 9)。每個資料集應有特徵Array(二維)以及Label Array(一維)。如前面提到的,每個名子應該要對應到全名以及單字的One-hot Encoding。比如說,"芳瑜"的特徵表示為"芳"、"瑜",以及原始的名子"芳瑜"。建構特徵表示時應依照個特徵出現的頻率篩選。特徵在訓練資料出現兩次或以上才納入。如果一個特徵被排除,這個特徵出現時應被歸為"_OtherFeature"。任何名子只要有出現未被納入的特徵,則其"_OtherFeature"的欄位值為1。

舉例而言,假設訓練資料集中有下面三個名子: 承恩、承德、恩賜。在經過特徵頻率篩選之後,只剩下以下特徵: 承、恩。其他特徵,如承恩、承德、恩賜、德、賜皆被排除。因此最後的特徵表示為:

Input _OtherFeature
承恩 1 1 1
承德 1 0 1
恩賜 0 1 1

最後應產生以下Numpy Array:

請列出每個Numpy Array的Shape以資查驗。

依照每筆資料其fold值切割為Training (fold <=6)、Validation (fold == 7)、Stacking (fold == 8)、Test (fold == 9)資料集。

使用One-hot Encoding建構資料變數

Q1.2 (10%):

使用sklearn.linear_model.LogisticRegression()建構Logistic Regression分類模型。利用Training與Validation調教Regularization Coefficient $c$。Grid Search的小值為$10^{-4}$,最大值是$1,000$,總共取20個點,使用等比級數間隔。取F-1 Score最大之Regularization Coefficient,印出此數值(以下稱bestc)。將Training與Validation合併後,令Regularizaiton Coefficient為bestc,訓練最終模型,並報告Test Data的Accuracy, Precision, Recall, 與F-1 Score。另外列出係數絕對值最大的20個特徵。注意應列出未取絕對值的係數數值,方知特徵的性別傾向。討論Prediction Performance與重要特徵的合理性。

找出F-1 Score最大之Regularization Coefficient,稱為bestc

將Training與Validation合併

令Regularizaiton Coefficient為bestc,訓練最終模型,並報告Test Data的Accuracy, Precision, Recall, 與F-1 Score。另外列出係數絕對值最大的20個特徵。

討論Prediction Performance與重要特徵的合理性

根據模型預測結果,預測準確率88%,Recall準確率89%略高於Precision準確率86%,整體來說預測表現算是還不錯,另外從圖表中也可以看出前20名的特徵都是一個字的,因此我們可以推測取一個字做為特徵比取兩個字更能判定性別,最後我們可以從係數看出正的值代表的是男性,負的代表是女性,前20名中多半都是判定女性的特徵

Q1.3 (10%):

使用sklearn.ensemble.RandomForestClassifier()建構Random Forest分類模型。利用Training與Validation調教Number of Tress (i.e., n_estimators)。Grid Search的小值為$5$,最大值是$1,000$,總共取10個點,使用等比級數間隔。取F-1 Score最大之n_estimators,印出此數值(best_nest)。將Training與Validation合併後,令n_estimators為best_nest,訓練最終模型,並報告Test Data的Accuracy, Precision, Recall, 與F-1 Score。另外列出最重要的20個特徵。討論Prediction Performance與重要特徵的合理性。

找出F-1 Score最大之n_estimators,稱為best_nest

將Training與Validation合併

令n_estimators為best_nest,訓練最終模型,並報告Test Data的Accuracy, Precision, Recall, 與F-1 Score。另外列出最重要的20個特徵。

討論Prediction Performance與重要特徵的合理性

根據預測結果,預測準確率接近0.84,Recall準確率0.84略高於Precision準確率0.81,相較於前面使用的LogisticRegression準確率下降了一些,整體預測結果還算可以的,另外從表中可以看到與前面LogisticRegression相同的是特徵前20名都是一個字,然而比較不一樣的是從RandomForestClassifier篩選出的重要特徵值很難從中判定性別,不像LogisticRegression有明顯的正負之別。

Q1.4 (10%):

使用sklearn.ensemble.GradientBoostingClassifier()建構Gradient Boosting Decision Tree (GBDT)分類模型。利用Training與Validation調教learning_rate與n_estimators。考慮以下Learning Rate: 0.1, 0.5, 1。每一個Learning Rate設n_estimator為1,500並估計一個GBDT分類器,計算1,500個Stages下Validation F-1 Score值,繪圖,並找出讓F-1 Score最大的Stage與F-1 Score最大值。對所有Learning Rate重複同樣程序,找出最佳的Learning Rate (稱best_lr) 與其對應的Number of Stages(best_nstg)。將Training與Validation合併後,令learning_rate為best_lr, n_estimators為best_nstg,訓練最終模型,並報告Test Data的Accuracy, Precision, Recall, 與F-1 Score。另外列出最重要的20個特徵。討論Prediction Performance與重要特徵的合理性。

對所有Learning Rate重複計算1,500個Stages下Validation F-1 Score值,繪圖,並找出讓F-1 Score最大的Stage與F-1 Score最大值

找出最佳的Learning Rate (稱best_lr) 與其對應的Number of Stages(best_nstg)

將Training與Validation合併

令learning_rate為best_lr, n_estimators為best_nstg,訓練最終模型,並報告Test Data的Accuracy, Precision, Recall, 與F-1 Score。另外列出最重要的20個特徵。

討論Prediction Performance與重要特徵的合理性

根據上面結果,預測準確率0.86,Recall準確率與Prcesion準確率的差距接近0.8是預測到目前為止最大的,整體來說預測結果介於Logistic Regression與Random Forest之間,然而不變的是前20名特徵清一色都是一個字,顯然一個字判別性別是比較精確的,但與RandomForestClassifier相同從特徵值很分辨出性別是男還是女,根據我的直覺猜測女生應該是佔大多數的。

Q1.5 (10%):

取用前面所建構的Logistic Regression, Random Forest, 與Gradient Boosting Decision Tree, 組合(Stacking)成一個新的分類器。我們使用Logistic Regression without Penalty建構這個Stacking分類器。訓練資料為Stacking資料集。各分類器輸入的特徵為男生預測機率(注意: 不是分類結果)。列出Stacking分類器的係數,討論係數的意義,並計算這個Stacking分類器在Test資料集的預測能力。

合併前面所建構的Logistic Regression, Random Forest, 與Gradient Boosting Decision Tree分類器預測stack訓練集的男性機率做為訓練Stacking分類器的特徵。

使用Logistic Regression without Penalty建構這個Stacking分類器。

列出Stacking分類器的係數,討論係數的意義。

我們可以看到Gradient Boosting Decision Tree分類器的係數(4.88)是當中最高的,因此整體來說會更偏向Gradient Boosting Decision Tree分類器

與前面訓練Stacking分類器特徵一樣,在預測Stacking分類器時應將前面所建構的Logistic Regression, Random Forest, 與Gradient Boosting Decision Tree分類器預測test預測集的男性機率合併做為特徵。

計算這個Stacking分類器在Test資料集的預測能力。

將Stacking分類器與前面所建構的Logistic Regression, Random Forest, 與Gradient Boosting Decision Tree分類器所預測的結果列表比較

小結

從以上圖表我們可以看出LogisticRegression的準確率是裡面當中最高的,但也只比StackingClassifier高出一點點,推測可能原因跟模型隨機切分資料的random_state有關,因此我們也不應該判定透過Stacking對不同分類器的預測結果再進行訓練是無效的,只是提升的幅度可能真的有限。

第二題 [Data Visualization via Dimensionality Reduction]

The department_id can uniquely identify an academic department. We do not care about the ranking of admission here, and you should ignore the "state" column. We only care about the "co-application" relations in this dataset. You should use student_id to identify a student applicant uniquely.

You can use this dataset to identify the name of a department_id. The school_name and department_name contain the "full name" of an academic department. To facilitate visualization, we also provide "shorter names" in school_name_abbr and department_name_abbr. The category_name is the field of an academic department. This field is essential in our visualization exercise since you should color each data point according to its category_name.

Data Preparation

Our focus is on the relationships between departments. To do this, we need to convert the raw data into a "matrix" representation. Each row represents an academic department, and each column represents a student applicant. The cell's value is one if a student applied for admission to the corresponding academic department, and 0 otherwise.

To avoid potential numerical problems, we only include an academic department if it received ten or more applications. Moreover, we only include a student applicant if he or she applied for more than one academic department.

Note that the two conditions should be satisfied "as is" in after preprocessing. For example, suppose a student applied for two departments in the original dataset, and one of the departments was removed. In that case, this student should be removed because the student only applied for one department in the processed dataset.

Report the top ten departments that received the most applications and the number of applications they received:

Q2.1 (10%): Visualize academic departments using the first eight principal components. Use your judgment to select multiple pairs of principal components to visualize. Discuss the visual patterns concerning department categories.

根據上圖表經過PCA降維之後,取第一主成分跟第二主成分來作圖可以看出醫藥衛生及社會類別被集中分在圖表的上半部,工程、製造及營建類別被分在圖表的下半部分,圖表左半部分則呈現大混亂的局勢,所有的類別都擠在一起,無法看出明顯分群。

根據上圖表經過PCA降維之後,取第三主成分跟第四主成分來作圖可以看出商業、管理及法律被集中分在圖表的上半部分,工程、製造及營建類別一樣被分在圖表下半部分,藝術及人文被集中分在圖表的最左半邊,剩下類別則都高度重疊在左半部分(藝術及人文右邊)

Q2.2 (10%): Visualize academic departments using multiple dimensional scaling. Consider both the metric and non-metric settings. Discuss the result.

小結

從上方圖表可以發現不管是Metric還是NonMetric經過MDS降維都無法看出明顯分群的趨勢,都呈現非常混亂的局勢

Q2.3 (10%): Visualize academic departments using Locally Linear Embedding. Consider three variations: (1) Use 20 neighbors to construct the weight matrix; (2) Use 40 neighbors to construct the weight matrix; (3) Perform PCA transformation first, and use the first 100 principal components as the input to LLE (with 20 neighbors). Discuss the result.

(1) Use 20 neighbors to construct the weight matrix
(2) Use 40 neighbors to construct the weight matrix
(3) Perform PCA transformation first, and use the first 100 principal components as the input to LLE (with 20 neighbors)

小結

本題第一、二小題不管取20個還是40個鄰居呈現的結果都差不多,類別都集中在右上方角落,因此著重說明有無進行PCA前處理所呈現結果的不同,我們可以看出經過PCA前處理分群結果有好上一些,推測原因可能是PCA將雜訊過濾掉,並找出比較好的特徵,但整體而言還是呈現非常混亂,因此LLE在這題來說可能不是一個適合的方法。

Q2.4 (10%): Visualize academic departments using Kernel PCA. You should at least consider the RBF and Cosine kernel. It is your responsibility to select reasonably good kernel parameters. Discuss the result.

RBF

從上方測試不同gamma值所呈現的分群結果,可以看出gamma小到10e-5時會有比較明顯的分群結果,醫藥衛生及社會福利被分在上半部分,工程、製造及營建勉強被分在下半部分,剩餘的gamma還是呈現高度重疊、混亂的情勢

Cosine

我們可以看出使用Cosinekernel比RBFkernel來的好,醫藥衛生及社會福利被分在右上部分,工程、製造及社會福利勉強集中在下半部分,但嚴格來說不管是使用Cosinekernel或RBFkernel大多數的類別還是呈現高度重疊、混亂的局勢。

Q2.5 (10%): Visualize academic departments using t-SNE. You should consider at least the Euclidian, Cosine, and Jaccard metric. Set numpy random seed so that your results can be repeated. Discuss the result.

Use Euclidian metric
Use Cosine metric
Use Jaccard metric

小結

從以上圖表我們可以看出使用Euclidian方法分群結果是最差的,所有類別都高度重疊擠在一起,而使用CosineJaccard方法分群結果是比較好的,有將各自類別集中在某個部分的趨勢,也是到目前為止分群結果最好的。

Q2.6 (10%) Select the most promising visualization method in the previous question and refine the result. You should color points by department category. Label each data point with its name so that we can quickly identify a data point on the picture. Moreover, you should try to reduce the problem caused by overlapping points and labels. Output an image that is large enough so that a user can easily identify a department and its neighbors. Jupyter Lab has limitations on the largest picture size. To overcome this problem, output the picture to a separate file and submit the file for grading. Your score depends on how useful, readable, and visually pleasing of your visualization results.

小結

延續前一題提到CosineJaccard方法有到目前為止比較好的分群結果,考量兩者的處理時間決定使用Cosine方法做為本題畫圖的visualization method,這邊使用Plotly套件作圖,與MatplotlibSeaborn相比能更好的與使用者互動,從圖表中的點點我們可以很清楚看到對應的系所和類別,最後因為礙於notebook cell 大小的關係可能無法看到完整的圖,因此附上網路連結(https://hopeful-panini-852c51.netlify.app/)